﻿using Gasgoo.DataProvider.EntityFramework.iToolLogger;
using Gasgoo.ShareLibrary.Framework.iDataProvider;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Gasgoo.DataProvider.ByEntityFramework
{
    public class DataStorageProviderByEntity : IDataStorageProvider
    {
        private readonly iToolLoggerContext context;

        public DataStorageProviderByEntity(string providerName, IServiceProvider provider, iToolLoggerContext context)
        {
            this.context = context;
        }
        public async Task AddOrUpdateAsync(string grainType, string key, string keyExtension, object value, Type type)
        {
            var val = await this.GetAsync(grainType, key, keyExtension, type); // old
            this.context.Attach(value).State = val == null ? Microsoft.EntityFrameworkCore.EntityState.Added : Microsoft.EntityFrameworkCore.EntityState.Modified;
            await this.context.SaveChangesAsync();
        }

        public async Task<object> GetAsync(string grainType, string key, string keyExtension, Type type)
        {
            try
            {
                return (await this.context.FindAsync(type, int.Parse(key)));
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        public Task<List<T>> QueryableAsync<T>(Queryable<T> queryable) where T : AbstractDataEntity
        {
            throw new NotImplementedException();
        }

        public async Task RemoveAsync(string grainType, string key, string keyExtension, object value)
        {
            this.context.Remove(value);
            await this.context.SaveChangesAsync();

        }
    }
}
